package com.xiashitech.agent.rule.usermatch.inst;

import com.google.auto.service.AutoService;
import com.xiashitech.agent.config.StartConfig;
import com.xiashitech.agent.dto.UserRequest;
import com.xiashitech.agent.instrumentation.redis.RedisData;
import com.xiashitech.agent.rule.usermatch.base.UserInfoMatchRule;
import com.xiashitech.agent.utils.JsonUtil;
import com.xiashitech.interfaces.agent.dto.AgentConfigDTO;
import ognl.Ognl;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.Date;
import java.util.List;

/**
 * 只做一层遍历，redis中的key即为用户id,返回值为string,其它遍历方式再增加UserInfoMatchRule匹配规则类
 * @param <REQUEST>
 */
//@AutoService(UserInfoMatchRule.class)
public class XSOgnlForJedisUserMatch<REQUEST> implements UserInfoMatchRule<REQUEST> {
    @Override
    public UserRequest extractUserInfo(REQUEST request) {
        if (request == null || !(request instanceof RedisData)) {
            return UserRequest.builder().build();
        }
        RedisData redisData = (RedisData)request;
        List<String> usernamekeys = AgentConfigDTO.getConfig().getUsernamekey();
        UserRequest userRequest = UserRequest.builder().requestDate(String.valueOf(new Date().getTime())).build();
        if(usernamekeys != null) {
            usernamekeys.forEach(userkey -> {
                try {
                    if(redisData.getField() != null) {
                        String userId = new String(redisData.getField());
                        String sessionId = new String(redisData.getKey());
                        Object userIdValueObj = JsonUtil.getObjectFromByteArray(redisData.getValue());
                        String userIdValue = "";
                        if(userIdValueObj != null) {
                            if(userIdValueObj instanceof String) {
                                userIdValue = (String)userIdValueObj;
                            } else {
                                userIdValue = getUserIdWithOngl(userIdValueObj);
                            }
                        }
                        if (userkey.equalsIgnoreCase(userId)) {
                            userRequest.setSessionId(sessionId);
                            userRequest.setUserid(userIdValue);
                        }
                    } else {
                        Object userIdValueObj = JsonUtil.getObjectFromByteArray(redisData.getValue());
                        String userIdValue = "";
                        if(userIdValueObj != null) {
                            if(userIdValueObj instanceof String) {
                                userIdValue = (String)userIdValueObj;
                            } else {
                                userIdValue = getUserIdWithOngl(userIdValueObj);
                            }
                        }
                        String sessionId = new String(redisData.getKey());
                        userRequest.setSessionId(sessionId);
                        userRequest.setUserid(userIdValue);
                    }
                } catch (Throwable e) {
                    StartConfig.throwableStackPrinter(e);
                }
            });
        }
        return userRequest;
    }

    private String getUserIdWithOngl(Object userIdObj) {
        String userIdPath = AgentConfigDTO.getConfig().getUseridpath().get(StartConfig.getParamValueFromKey(StartConfig.systemId));
        String userIdValue = "";
        try {
            if (":".indexOf(userIdPath) < 0) // 认为配置 key 是正常的，不是用于截取之类的，在永达汽车中配置的是 USERID: ,不是用于 Ognl，是用来截取的
                userIdValue = String.valueOf(Ognl.getValue(userIdPath, userIdObj));
        } catch (Exception e) {
            StartConfig.throwableStackPrinter(e);
        }
        return userIdValue;
    }

    @Override
    public Integer getOrder() {
        return 4;
    }
}
